﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace SharpSoft.WPF.Converters
{
    /// <summary>
    /// 将空白字符转为可识别转义字符
    /// </summary>
    public class WhiteSpaceTextConverter : IValueConverter
    {
        private static List<(char c, string display, string des)> mapping = new List<(char c, string display, string des)>();
        static WhiteSpaceTextConverter()
        {
            mapping.Add(('\n', "\\n", "[换行符]"));
            mapping.Add(('\r', "\\r", "[回车符]"));
            mapping.Add(('\t', "\\t", "[制表符]"));
            mapping.Add(('\f', "\\f", "[换页符]"));
            mapping.Add(('\b', "\\b", "[退格符]"));
            mapping.Add(('\a', "\\a", "[响铃符]"));
            mapping.Add(('\v', "\\e", "[垂直制表符]"));
            mapping.Add(('\0', "\\0", "[终止符]"));
        }

        private static (char c, string display, string des)? getByChar(char c)
        {
            foreach (var item in mapping)
            {
                if (item.c == c)
                {
                    return item;
                }
            }
            return null;

        }

        public string GetUnicode(char c)
        {
            var data = UnicodeEncoding.Unicode.GetBytes(c.ToString());
            var hex = HexHelper.BytesToHexString(data);
            return $"\\u{hex}";
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is string str))
            {
                str = System.Convert.ToString(value);
            }
            if (string.IsNullOrEmpty(str))
            {
                return str;
            }
            StringBuilder sb = new StringBuilder();
            foreach (var item in str)
            {
                var g = getByChar(item);
                if (g.HasValue)
                {
                    switch (this.Mode)
                    {
                        case ConvertMode.Display:
                            sb.Append(g.Value.display);
                            break;
                        case ConvertMode.Description:
                            sb.Append(g.Value.des);
                            break;
                        default:
                            break;
                    }
                }
                else
                {
                    sb.Append(item);
                }
            }
            return sb.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is string str))
            {
                str = System.Convert.ToString(value);
            }
            if (string.IsNullOrEmpty(str))
            {
                return str;
            }
            switch (this.Mode)
            {
                case ConvertMode.Display:
                    foreach (var item in mapping)
                    {
                        str = str.Replace(item.display, item.c.ToString());
                    }
                    break;
                case ConvertMode.Description:
                    foreach (var item in mapping)
                    {
                        str = str.Replace(item.des, item.c.ToString());
                    }
                    break;
                default:
                    break;
            }
            return str;
        }

        public ConvertMode Mode { get; set; }

        public enum ConvertMode
        {
            Display,
            Description

        }

        public static class HexHelper
        {
            /// <summary>
            /// 将十六进制字符串转换为字节数组
            /// </summary>
            /// <param name="hex"></param>
            /// <param name="autoPaddingLeft">当字符数量为奇数时，是否在左侧补一个0</param>
            /// <returns></returns>
            public static byte[] HexStringToBytes(string hex, bool autoPaddingLeft = false)
            {
                hex = hex.Trim();
                if (hex.Contains(" "))
                {
                    var hexs = hex.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    byte[] data = new byte[hexs.Length];
                    for (int i = 0; i < hexs.Length; i++)
                    {
                        data[i] = System.Convert.ToByte(hexs[i], 16);
                    }
                    return data;
                }
                else
                {
                    if (hex.Length % 2 != 0)
                    {
                        if (autoPaddingLeft)
                        {
                            hex = "0" + hex;
                        }
                        else
                        {
                            throw new Exception("十六进制字符串字符数必须为2的倍数。");
                        }
                    }
                    var count = hex.Length / 2;
                    byte[] data = new byte[count];
                    for (int i = 0; i < count; i++)
                    {
                        data[i] = System.Convert.ToByte(hex.Substring(i * 2, 2), 16);
                    }
                    return data;
                }
            }
            /// <summary>
            /// 将字节数组转换为16进制字符串
            /// </summary>
            /// <param name="data"></param>
            /// <param name="splitor">分隔符</param>
            /// <returns></returns>
            public static string BytesToHexString(byte[] data, string splitor = "")
            {
                string[] strs = new string[data.Length];
                for (int i = 0; i < data.Length; i++)
                {
                    strs[i] = data[i].ToString("X2");
                }
                return string.Join(splitor, strs);
            }
        }
    }
}
